<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;




use app\common\facade\Func;
use think\Db;

class Coupons extends ApiCommon
{
    protected $table = 'lite_coupons';
    protected $activityTable = 'lite_activity';
    protected $recordTable = 'lite_coupons_record';

    public function __construct()
    {
        parent::__construct();
    }

    public function send()
    {
       $where = ['is_deleted' => 0 ,'status' => 2];

       $list = db($this->table)->where($where)->order('id', 'desc')->select();

       $productIds = array_column($list, 'product_id');
       $ids = array_column($list, 'id');

       $hasGetCoupons = db::table($this->recordTable)->where(['open_id' => $this->openid])->where('coupons_id', 'in', $ids)->column('id, coupons_id', 'id');

       $productData = [];
       foreach ($productIds as $productId){
           if($productId == -1){
               $productData[] = '全场通用';
           }else{
               $productItem = explode(',', $productId);
               $product= db($this->activityTable)->where('id', 'in', $productItem)->column('id,name', 'id');
               $productData[] = implode(',', $product);
           }
       }


       $hasGetCouponsStatus = array_count_values($hasGetCoupons);

        foreach ($list as $key => $value){
           if($list[$key]['use_type'] == 1){
               $list[$key]['use_type'] = '报名';
           }else if($list[$key]['use_type'] == 2){
               $list[$key]['use_type'] = '商城';
           }else{
               $list[$key]['use_type'] = '通用';
           }
           $list[$key]['use_start_time'] = substr($list[$key]['use_start_time'], 0 ,10);
           $list[$key]['use_end_time'] = substr($list[$key]['use_end_time'], 0 ,10);
           $list[$key]['product_id'] = $productData[$key];
           //可领取状态
           if(!isset($hasGetCouponsStatus[$value['id']]) || $value['limit_count'] == -1 || $value['limit_count'] > $hasGetCouponsStatus[$value['id']]){
               $list[$key]['get_status'] = true;
           }else{
               $list[$key]['get_status'] = false;
           }
       }

       $res = $list;

       $this->success('', $res);
    }

    public function get()
    {
        //优惠券码
        $couponsCode = $this->request->param('coupons_code');
        if(!empty($couponsCode)){
            $coupons_code =  base64_decode($couponsCode);
            $code = db::table($this->table)->where(['coupons_code' => $coupons_code])->value('id');
        }else{
            $code = $this->request->param('code');
        }

        if(empty($code)){
            $this->error('领取失败,无效code!');
        }
        $coupons = db($this->table)->where(['id' => $code])->find();
        if(empty($coupons)){
            $this->error('领取失败,无效优惠券!');
        }
        //限制会员
        if(!empty($coupons['user_ids']) && $coupons['user_ids'] != -1){
            if(!in_array($this->openid, explode(',', $coupons['user_ids']))){
                $this->error('领取失败,您不是指定用户！');
            }
        }
        $recordModel = db::table($this->recordTable);
        $recordCount = $recordModel->where(['open_id' => $this->openid, 'coupons_id' => $coupons['id']])->count();
        if($coupons['limit_use_type'] == 1){ //时效（1固定时段（xx-yy时间），2领取N天内有效）
            $startTime = $coupons['use_start_time'];
            $endTime = $coupons['use_end_time'];
        }else if($coupons['limit_use_type'] == 2){
            $startTime = date('Y-m-d H:i:s');
            $endTime = date('Y-m-d H:i:s', strtotime($startTime) + $coupons['limit_use_day'] * 24* 3600);
        }else{
            $startTime = null;
            $endTime = null;
        }
//        $limit = ($coupons['limit_count'] == -1 || $coupons['limit_count'] > $recordCount && $coupons['count'] > $coupons['has_count']);
        $limit1 = $coupons['limit_count'] == -1 || $coupons['limit_count'] > $recordCount; //不限制领取次数
        $limit2 = $coupons['count'] == -1 || $coupons['count'] > $coupons['has_count']; //优惠券数量足够
        $limit = $limit1 && $limit2;
        $now = time();
        if($coupons['limit_use_type'] == 1){
            if($now < strtotime($coupons['use_start_time']) || $now > strtotime($coupons['use_end_time'])){
                //更新优惠券状态
                $this->updateCouponsStatus($code, 3);
                $this->error('领取失败,未在领取有效期领取！');
            }
        }
        //数量限制
        if($coupons['count'] != -1 && $coupons['count'] <= $coupons['has_count']){
            //更新优惠券状态
            $this->updateCouponsStatus($code, 4);
            $this->error('领取失败,优惠券已被领取完！');
        }
        if($limit){
            $record = [
                'open_id' => $this->openid,
                'coupons_id' => $coupons['id'],
                'create_at' => date('Y-m-d H:i:s'),
                'status' => 1,
                'use_start_time' => $startTime,
                'use_end_time' => $endTime,
                'coupons_type' => $coupons['type'], //优惠券1折扣券，2满x减n,3无条件立减
                'use_type' => $coupons['use_type'], // 使用类型（1.活动，2商城 3 通用）
                'limit_use_type' => $coupons['limit_use_type'], // 时效（1固定时段（xx-yy时间），2领取N天内有效）3无限制
                'product_id' => $coupons['product_id'],
            ];
            // 启动事务
            Db::startTrans();
            $res = $recordModel->insert($record);
            if($res){
                //限制优惠券总的领取次数，防并发的情况
                if($coupons['count'] != -1){
                    $result = db::table($this->table)->where(['id' => $code])->where('has_count', '<', $coupons['count'])->setInc('has_count', 1);
                }else{
                    $result = db::table($this->table)->where(['id' => $code])->setInc('has_count', 1);
                }
                if($result){
                    //判断优惠券数量
                    if($coupons['count'] == -1 || $coupons['count'] >= ($coupons['has_count'] + 1)){
                        Db::commit();
                        $this->success('领取成功！', $res);
                    }else{
                        Db::rollback();
                        //更新优惠券状态
                        $this->updateCouponsStatus($code, 4);
                        $this->error('优惠券已被领完！');
                    }
                }else{
                    Db::rollback();
                    //更新优惠券状态
                    $this->updateCouponsStatus($code, 4);
                    $this->error('领取失败,优惠券已被领完！');
                }
            }else{
                Db::rollback();
            }
        }else{
            $this->error('超过领取次数！' );
        }
    }

    private function updateCouponsStatus($code, $int)
    {
        return db($this->table)->where(['id' => $code])->update(['status' => $int]);
    }



    public function myCoupons()
    {
        //'is_deleted' => 0 ,'status' => 2
        $where = ['record.is_deleted' => 0];

        $list = db::table($this->recordTable)->alias('record')->field('record.*,coupons.*,record.status as status')->where(['open_id' => $this->openid])
            ->where($where)->leftJoin($this->table. ' coupons', 'coupons.id = record.coupons_id')
            ->order('record.status', 'asc')
            ->order('record.id', 'desc')
            ->select();
//        var_dump(db::table($this->recordTable)->alias('record')->field('record.*,coupons.*,record.status as status')->where(['open_id' => $this->openid])
//            ->where($where)->leftJoin($this->table. ' coupons', 'coupons.id = record.coupons_id')
//            ->order('record.status', 'asc')
//            ->order('record.id', 'desc')
//            ->getLastSql());exit;


        $productIds = array_column($list, 'product_id');

        $productData = [];
        foreach ($list as $key => $activity){
            if($activity['product_id'] == -1){
//                $productData[] = '全场通用';
                if($list[$key]['activity_type'] == 1){
                    $list[$key]['product_id'] = '签证';
                }
                if($list[$key]['activity_type'] == 2){
                    $list[$key]['product_id'] = '海外赛事';
                }
                if($list[$key]['activity_type'] == 3){
                    $list[$key]['product_id'] = '国内赛事';
                }
            }else{
                $productItem = explode(',', $activity['product_id']);
                $product= db($this->activityTable)->where('id', 'in', $productItem)->column('id,name', 'id');
                $list[$key]['product_id'] = implode(',', $product);
            }

            if($list[$key]['use_type'] == 1){
                $list[$key]['use_type'] = '报名';
            }else if($list[$key]['use_type'] == 2){
                $list[$key]['use_type'] = '商城';
            }else{
                $list[$key]['use_type'] = '通用';
            }
            $list[$key]['use_start_time'] = substr($list[$key]['use_start_time'], 0 ,10);
            $list[$key]['use_end_time'] = substr($list[$key]['use_end_time'], 0 ,10);
        }


        $res = $list;

        $this->success('', $res);
    }
}